<template>
  <view class="login-container">
    <!-- 基础表单校验 -->
    <uni-forms ref="formRef" :rules="rules" :modelValue="form">
      <uni-forms-item label="手机号" required name="loginname">
        <uni-easyinput v-model="form.loginname" placeholder="请输入手机号" />
      </uni-forms-item>
      <uni-forms-item label="密码" required name="password">
        <uni-easyinput
          type="password"
          v-model="form.password"
          placeholder="请输入密码"
        />
      </uni-forms-item>
    </uni-forms>
    <button
      type="submit"
      style="background-color: #c82519; color: white"
      @click="onLogin"
    >
      登 录
    </button>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { login } from '@/api/user'
import { useUserStore } from '@/store/user'
const store = useUserStore()

const formRef = ref()

const form = ref({
  loginname: '17704051019',
  password: '123456'
})

const rules = ref({
  loginname: {
    rules: [
      {
        required: true,
        errorMessage: '手机号不能为空'
      },
      {
        pattern: /^1[3-9]\d{9}$/,
        errorMessage: '手机号不合法'
      }
    ]
  },
  password: {
    rules: [
      {
        required: true,
        errorMessage: '密码不能为空'
      },
      {
        pattern: /^\w{5,}/,
        errorMessage: '密码至少5位'
      }
    ]
  }
})

// 登录
const onLogin = async () => {
  try {
    await formRef.value.validate()

    const res = await login({
      loginname: form.value.loginname,
      password: form.value.password
    })

    if (res.code === 200) {
      // 保存token信息到仓库中
      // store.setUser(res.data as any)
      store.setUser(res.data)

      uni.showToast({
        icon: 'success',
        title: '登录成功~',
        success: () => {
          setTimeout(() => {
            // 路由跳转
            uni.reLaunch({
              url: '/pages/home/index'
            })
          }, 500)
        }
      })
    } else {
      uni.showToast({
        icon: 'none',
        title: '用户名或密码失败'
      })
    }
  } catch (error) {
    console.log('---error---', error)
  }
}
</script>

<style lang="less" scoped>
.login-container {
  padding: 20rpx;
}
</style>
